package com.cino.demos.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtil {

    private String endpoint = "oss-cn-guangzhou.aliyuncs.com";
    private String accessKeyId = "LTAI5tDs4iUrzFcKbPdC9iXi"; // 你的AccessKey ID
    private String accessKeySecret = "sPTlcc4yLMN4CmTyfuxX4MX5r87j8A"; // 你的AccessKey Secret
    private String bucketName = "cino-oss";

    public String upload(MultipartFile file) throws IOException {
        // 获取上传文件的输入流
        InputStream inputStream = file.getInputStream();

        // 定义文件的唯一标识
        String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();

        // 上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName,fileName,inputStream);

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder url = new StringBuilder("https://");
        url
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(fileName);


        //关闭ossClient
        ossClient.shutdown();
        return url.toString();
    }

}
